<?php

class Subscriber_model extends MY_Model {
    
    var $_table = 'subscriber';

    public function __construct() {

        parent::__construct();

	}

	private function head()
	{
		return $this->db
			->select("SQL_CALC_FOUND_ROWS s.*, sg.name AS group_name", FALSE)
        	->from('subscriber_group AS sg')
        	->join('subscriber AS s', 's.group_id = sg.id');
	}

	public function add($data = array())
	{
        $this->db->insert('subscriber', $data);
    }

	public function gets($options = array(), $limit = 0, $offset = 0)
	{
		$this->head();
		
		// WHERE
		if(isset($options['user_id']))
			$this->db->where('s.user_id', $options['user_id']);
		
		if(isset($options['group_id']))
			$this->db->where('s.group_id', $options['group_id']);
		
		if(isset($options['gender']))
			$this->db->where('s.gender', $options['gender']);

        return parent::my_result($limit, $offset);
    }

	public function get($options = array())
	{
		$this->head();

		// WHERE
		if(isset($options['id']))
			$this->db->where('s.id', $options['id']);
		
		$q = $this->db->get();

        if (!$q->num_rows())
            return false;

        return $q->row();
    }
	
	public function search($options, $limit = 0, $offset = 0)
	{
		$this->head();
		
		// WHERE
		if(isset($options['user_id']))
			$this->db->where('s.user_id', $options['user_id']);
		
		if(isset($options['group_id']))
			$this->db->where('s.group_id', $options['group_id']);
		
		if(isset($options['gender']))
			$this->db->where('s.gender', $options['gender']);

		// LIKE 
		$this->db->or_like(array(
                's.address' => $options['needle'],
                's.firstname' => $options['needle'],
                's.lastname' => $options['needle']
            ));
		
        return parent::my_result($limit, $offset);
	}

	public function edit($data = array(), $options = array())
	{
        $this->db->update('subscriber', $data, $options);
    }

	public function delete($options = array())
	{
        $this->db->delete('subscriber', $options);
    }
}

/* End of file subscriber_model.php */
